Skip to content

淺談 Git Commit 規範

TLDR

  • Git Commit 應遵循 Angular Commit Format,結構包含 Header(必填)、Body(選填)與 Footer(選填)。
  • Header 格式為 <type>(<scope>): <short summary>,其中 type 須符合規範(如 feat, fix, docs 等)。
  • 建議使用 git commit.template 設定全域或專案級的 Commit 模板,以確保團隊成員遵循統一格式。
  • 透過 git config --global commit.cleanup strip 可自動移除 Commit 訊息中的註解行,避免污染紀錄。
  • 關聯 Issue 或 PR 時,建議使用 Closes #123Fixes #123 等關鍵字,以利自動化管理。

Commit Format 結構

Angular Commit Format 將訊息分為三個部分,各部分之間需以空行隔開。

xml
<header>
<BLANK LINE>
<body>
<BLANK LINE>
<footer>

Header 規範

Header 是唯一必填項目,格式為 <type>(<scope>): <short summary>

  • Type:用於分類變更性質,常見類型包括 feat (新功能)、fix (修復錯誤)、docs (文件更新)、refactor (重構)、perf (效能優化)、test (測試)、build (打包/依賴變更)、ci (CI 設定變更)。
  • Scope:標註受影響的模組或套件,若無明確範圍可省略。
  • Short Summary:簡潔描述變更內容。建議使用祈使句(如 "change" 而非 "changed")、首字母不需大寫、句尾不加句號。
  • Body:說明變更動機與前後行為對比。若變更簡單可省略。
  • Footer:用於標註 BREAKING CHANGE(重大不相容變更)或 DEPRECATED(棄用資訊)。亦可用於關聯 Issue Tracker,例如在 GitHub 或 GitLab 中使用 Closes #123 即可在合併時自動關閉對應需求單。

設定 Git Commit Template

為了避免遺忘規範,可透過 Git 內建的 Template 功能統一格式。

設定步驟

  1. 建立 .gitmessage.txt 檔案,內容包含各欄位的說明與規範。
  2. 使用以下指令進行全域設定:
git
git config --global commit.template ~/.gitmessage.txt
git config --global commit.cleanup strip

設定說明

  • commit.template:指定模板檔案路徑。
  • commit.cleanup strip:確保在 Commit 時,自動移除以 # 開頭的註解行與多餘空行。

TIP

Git 的設定優先級為:Local (.git/config) > Global (~/.gitconfig) > System (/etc/gitconfig)。若需針對特定專案設定,請移除 --global 參數。

各版控軟體支援度

並非所有 GUI 工具皆會自動處理 # 註解行,建議檢查工具設定:

  • GitKraken:需手動勾選「Removes comments from commit messages」。
  • Sourcetree:3.4.20 版本後已正式支援 Git Commit Template。
  • Git Extensions:預設會自動忽略 # 開頭的註解行。

異動歷程

    • 初版文件建立。
    • 更新 Windows 版 Sourcetree 3.4.20 支援 Git Commit Template 功能。
    • 修正設定檔位置的說明。